package cn.niit.letuseatdemo.controller.user;

import cn.niit.letuseatdemo.common.Constants;
import cn.niit.letuseatdemo.entity.domain.Admin;
import cn.niit.letuseatdemo.entity.domain.User;
import cn.niit.letuseatdemo.entity.vo.response.BaseResponse;
import cn.niit.letuseatdemo.service.AdminService;
import cn.niit.letuseatdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;

import javax.servlet.http.HttpServletRequest;

/*
* @Description:用户登录（网页版 ）
* @Author: Zhang Shiqi
* @CreateTime： 2022/10/31 0:17
 * @param: null
 * @return: null
**/
@Controller
public class UserLoginController {
    @Autowired
    private UserService userService;

    /**
    * @Description:  显示登录页面
    * @Author: Zhang Shiqi
    * @CreateTime： 2022/10/22 13:51
    * @return: java.lang.String
    **/

    @GetMapping("/user/login")
    public String loginIndex(){
        return "/user/login";
    }

    /*
    * @Description: 得到页面信息，验证输入与身份
    * @Author: Zhang Shiqi
    * @CreateTime： 2022/10/31 0:19
     * @param: userTel
     * @param: password
     * @param: verifyCode
     * @param: request
     * @return: java.lang.String
    **/
    @PostMapping("/user/login")
    public String login(String userTel, String password, String verifyCode, HttpServletRequest request) {
        System.out.println("userTel = " + userTel + " password = " + password + "verifyCode = " + verifyCode);

        if (!StringUtils.hasLength(verifyCode)) {
            request.setAttribute("errorMsg", "验证码不能为空！");
            return "/user/login";
        }
        if (!StringUtils.hasLength(userTel) || !StringUtils.hasLength(password)) {
            request.setAttribute("errorMsg", "账号或者密码不能为空！");
            return "/user/login";
        }

        //拿去session中保存的验证码
        String kaptchaCode = request.getSession().getAttribute("verifyCode") + "";
        if (!verifyCode.equals(kaptchaCode)) {
            request.setAttribute("errorMsg", "验证码错误！");
            return "/user/login";
        }

        User user= userService.getUserByUserTelPassword(userTel,password);


        //验证账号密码是否正确  数据库
        if (null != user){

            request.getSession().setAttribute(Constants.ADMIN_SESSION_USER_ID_KEY,user);//验证账号是否正确
            request.getSession().setAttribute(Constants.ADMIN_SESSION_USER_KEY,user);

            //验证通过
            //return "index";
            return "redirect:/user/index";
        }else {
            //账号或密码错误
            request.setAttribute("errorMsg","账号或密码错误！");
            return "/user/login";
        }
    }
}
